use std::{collections::HashMap, fs, sync::Arc};

use arc_swap::ArcSwap;
use once_cell::sync::Lazy;
use fancy_regex::Regex;

use crate::base::{Error, Result};
use serde::{Deserialize, Serialize};

use super::get_config_path;
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct RegexItem {
    name: String,
    regex_exp: String,
    err_msg: String,
}

static REGEX_MAP: Lazy<ArcSwap<HashMap<String,(Regex,String)>>> =
    Lazy::new(|| ArcSwap::from_pointee(HashMap::new()));

pub fn init_regex_config() -> Result<()> {
    let file_path = format!("{}/config_files/regex.yaml", get_config_path());
    let conf_str = fs::read_to_string(file_path)?;
    let confs: Vec<RegexItem> = serde_yaml::from_str(&conf_str).or_else(|err| {
        Err(Error::Conf(format!("解析配置文件regex.yaml出错，错误信息{}", err)))
    })?;
    let mut regex_map:HashMap<String,(Regex,String)>=HashMap::new();
    for conf in confs.into_iter() {
        let reg=Regex::new(conf.regex_exp.as_str())?;
        regex_map.insert(conf.name, (reg,conf.err_msg));
    }
    REGEX_MAP.store(Arc::new(regex_map));
    Ok(())
}
pub fn is_exist_regex(name: &str) -> bool {
    REGEX_MAP.load().contains_key(name)
}

pub fn parse_regex(name: &str,value:&str) -> Result<()> {
    match REGEX_MAP.load().get(name) {
        Some((reg,msg)) => {
            if let Ok(is_ok)=reg.is_match(value) {
                if is_ok {
                   return Ok(());
                }
            }
            Err(Error::Conf(format!("无效值{},{}", value,msg)))
        },
        None => Err(Error::Conf(format!("规则表达式配置文件{}不存在", name))),
    }
}
